package com.qf.listener;

import com.qf.constant.RabbitMQConstants;
import com.qf.model.StandardSubmit;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;

/**
 * @author dell
 * @version V1.0
 * @Date 2022/6/9 17:21:29
 *
 *- 监听RABBITMQ中的状态报告"report_update_topic"，
 *   - 更新下行日志的状态报告，
 *   - 有可能会出现状态报告比下行日志先处理的情况，
 *   - 这种情况下可以利用延迟队列来处理，延迟个10秒再做状态报告更新。
 *
 *
 */
@Component
@Slf4j
public class UpdateListener {

    //Elasticsearch 的客户端
    @Autowired
    private RestHighLevelClient restHighLevelClient;

    @Value("${log-index}")
    private String logIndex;

    @RabbitListener(queues = RabbitMQConstants.TOPIC_UPDATE_SMS_REPORT)
    public void receiverSmsSendLog(Message message, Channel channel, StandardSubmit standardSubmit){
        try {
            Thread.sleep(100);

            String newIndex = logIndex + new SimpleDateFormat("yyyy").format(new Date());

            log.info("监听RABBITMQ中的状态报告  开始执行");

            //封装数据
            UpdateRequest updateRequest = new UpdateRequest();
            updateRequest.index(newIndex);
            updateRequest.id(standardSubmit.getSequenceId());

            HashMap<String, Object> map = new HashMap<>();

            /**
             * 手机接收的状态值  0 成功 1 等待 2 失败
             */
            //private Integer reportState;        //....  // ok
            map.put("reportState", standardSubmit.getReportState());

            /**
             * 状态的错误码
             */
            //private String errorCode;           // 指定出现问题时的错误码
            map.put("errorCode", standardSubmit.getErrorCode());

            updateRequest.doc(map);


            //更新日志
            UpdateResponse update = restHighLevelClient.update(updateRequest, RequestOptions.DEFAULT);
            String result = update.getResult().toString();

            if (result.equalsIgnoreCase("updated")){
                log.info("[搜索模块]  修改日志成功");
                //手动ack
                channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
            }else {
                log.error("[搜索模块]  修改日志失败");
                channel.basicNack(message.getMessageProperties().getDeliveryTag(), false,true);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}